package de.openlaboratory.elib.controller.servlets;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.ItemIterable;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;

import de.openlaboratory.cmis.core.OpenLabSession;
import de.openlaboratory.elib.core.LogManager;
import de.openlaboratory.elib.core.UserResources;
import de.openlaboratory.elib.model.ImportFile;
import de.openlaboratory.elib.utilities.Operation;

public class ImportServlet extends GenericDataServlet
{
	private static final long serialVersionUID = 1183063826482544696L;

	private static final String SERVLET_DESCRIPTION = "Document Import Functionalities";
	private static final String LIST_OBJECTS = "/WEB-INF/eLibListFiles.jsp";
	private static final String ELIB_DESKTOP = "/WEB-INF/eLibDesktop.jsp";
	private static final String ELIB_DESKTOP_MENU = "/WEB-INF/eLibDesktopMenu.jsp";

	ImportFile newDataObject;

	@Override
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		messages = new HashMap<String, String>();
		request.setAttribute("messages", messages);

		String action = (String) request.getParameter("elib_action");
		String elibNamespace = (String) request.getParameter("elib_ns");
		String elibRepository = (String) request.getParameter("elib_repository");

		Operation op = Operation.fromString(action);

		String page = null;

		switch (op)
		{
			case READ:
				newDataObject = (ImportFile) getFileFromServletRequest(newDataObject, request);
				page = readDataObject(request, newDataObject);
				break;
			default:
				page = listFilesCmis(request);
				break;
		}

		configuration.setMainPage(page);

		configuration.setStyleSheets(null);
		configuration.addStyleSheets("file-import.css");
		configuration.setJavaScripts("fileImport.js");
		configuration.setJavaScripts("pdfobject.js");
		configuration.setTitle(SERVLET_DESCRIPTION);
		configuration.setMenu(ELIB_DESKTOP_MENU);
		configuration.setMenuItems(page);

		request.setAttribute("configuration", configuration);

		LogManager.logMessage("submitting response...");
		switch (op)
		{
			case READ:
				// Write XML to response.
				response.setContentType("application/xml");
				response.getWriter().write(page);
				LogManager.logMessage("Send XML...");
				break;
			default:
				RequestDispatcher view = request.getRequestDispatcher(ELIB_DESKTOP);
				view.forward(request, response);
				break;
		}
	}

	private String readDataObject(HttpServletRequest request, ImportFile file)
	{
		file.readDocumentInfo();

		LogManager.logMessage("Looking up Thumbnail file");

		// "C:\\Users\\xeiojt\\Desktop\\DATA\\USB-Stick\\eBooks\\SAP EWM100.pdf";
		String thumbnail_file = file.getFullPath().replace("\\", "\\\\");
		String pdf_file = thumbnail_file;

		LogManager.logMessage(String.format("Thumbnail file: %s", thumbnail_file));

		String xmlData = "";

		xmlData = xmlData.concat("<?xml version=\"1.0\"?>");
		xmlData = xmlData.concat("<data>");
		xmlData = xmlData.concat("  <item id=\"path.local\">");
		xmlData = xmlData.concat("    <name>" + file.getName() + "</name>");
		xmlData = xmlData.concat("    <pages>" + file.getPages() + "</pages>");
		xmlData = xmlData.concat("    <preview><![CDATA[data?img&" + thumbnail_file + "]]></preview>");
		xmlData = xmlData.concat("    <document><![CDATA[data?pdf&" + pdf_file + "]]></document>");
		xmlData = xmlData.concat("  </item>");
		xmlData = xmlData.concat("</data>");

		return xmlData;
	}

	private <T> Object getFileFromServletRequest(T o, HttpServletRequest request)
	{
		ImportFile file = null;
		String name = request.getParameter("file_name").replace('?', '\\');

		LogManager.logMessage(String.format("File requested (%s)", name));
		file = new ImportFile(name);

		LogManager.logMessage(String.format("File read (%s)", file.getName()));

		return file;
	}

	private String listFiles(HttpServletRequest request)
	{
		List<ImportFile> files = new ArrayList<ImportFile>();

		Dictionary<String, Path> rootPaths = new Hashtable<String, Path>();

		rootPaths.put("Studium", Paths.get("C:\\Users\\xeiojt\\Desktop\\DATA\\My Box Files\\Studium"));
		rootPaths.put("eBooks", Paths.get("C:\\Users\\xeiojt\\Desktop\\DATA\\USB-Stick\\eBooks"));

		Enumeration<String> keys = rootPaths.keys();

		while (keys.hasMoreElements())
		{
			String key = (String) keys.nextElement();
			Path path = (Path) rootPaths.get(key);

			if (path.isAbsolute())
			{
				try (DirectoryStream<Path> ds = Files.newDirectoryStream(path))
				{
					for (Path p : ds)
					{
						ImportFile f1 = new ImportFile(p);
						files.add(f1);
					}

				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}

		request.setAttribute("files", files);

		return LIST_OBJECTS;
	}

	private String listFilesCmis(HttpServletRequest request)
	{
		List<ImportFile> files = new ArrayList<ImportFile>();
		List<Repository> repositories = UserResources.getInstance(null).getRepositories();

		for (Repository r : repositories)
		{
			Session session = r.createSession();
			Folder root = session.getRootFolder(); // String folderId = r.getRootFolderId();
			LogManager.logMessage("Folder root: " + root.getId() + "; " + root.getName() + "; " + root.getPath());
			
			ItemIterable<CmisObject> children = root.getChildren();
			Iterator<CmisObject> c = children.iterator();

			while (c.hasNext())
			{
				CmisObject o = (CmisObject) c.next();
				
				if (BaseTypeId.CMIS_DOCUMENT.equals(o.getBaseTypeId()))
				{
					LogManager.logMessage("File found: " + o.getName() + " which is of type " + o.getType().getDisplayName());
				}
				else if (BaseTypeId.CMIS_FOLDER.equals(o.getBaseTypeId()))
				{	
					LogManager.logMessage("Folder found: " + o.getName() + " which is of type " + o.getType().getDisplayName());
				}
				
				ImportFile f1 = new ImportFile(o.getProperty("FULL_PATH").toString());
				files.add(f1);
			}

			for (CmisObject o : children)
			{
				System.out.println(o.getName() + " which is of type " + o.getType().getDisplayName());
			}
		}

		request.setAttribute("files", files);

		return LIST_OBJECTS;
	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo()
	{
		return SERVLET_DESCRIPTION;
	}
}